import React, { Component,createRef } from 'react'
import { Form, Input, Button, Card,message } from 'antd';
import E from 'wangeditor'
import { updateArt ,getArt } from '@api'
const layout = {
  labelCol: {
    span: 4,
  },
  wrapperCol: {
    span: 20,
  },
};
const tailLayout = {
  wrapperCol: {
    offset: 10,
    span: 14,
  },
};

export default class ArtAdd extends Component {
	constructor() {
	   super();
		 this.state  = {
			 editor:null,
			 initArticle: null
		 }
		 this.editorWrap = createRef()
	}
  render() {
    return (
      <Card title="编辑文章">
				{
					this.state.initArticle
					?
					<Form
					      {...layout}
					      name="basic"
								initialValues = { this.state.initArticle }
					      onFinish={this.submitForm}
					    >
					      <Form.Item
					        label="文章标题"
					        name="title"
					        rules={[
					          {
					            required: true,
					            message: '请填写文章标题!',
					          },
					        ]}
					      >
					        <Input placeholder="文章标题"/>
					      </Form.Item>
					
					      <Form.Item
					        label="作者"
					        name="author"
					        rules={[
					          {
					            required: true,
					            message: '请填写作者!',
					          },
					        ]}
					      >
					        <Input  placeholder="请输入作者"/>
					      </Form.Item>
								<Form.Item
								  label="简介"
								  name="desc"
								  rules={[
								    {
								      required: false,
								      message: '',
								    },
								  ]}
								>
								  <Input.TextArea  placeholder="请输入描述"/>
								</Form.Item>
								<Form.Item
								  label="文章详情"
								  name="content"
								
								>
								  <div id="editor" ref={this.editorWrap}/>
								</Form.Item>
					      <Form.Item {...tailLayout}>
					        <Button type="primary" htmlType="submit">
					          提交
					        </Button>
					      </Form.Item>
					    </Form>
							:
							''
				}
			</Card>	
    )
  }
	componentDidMount(){
		// 调用 获取 文章
		this.getInitArt();
	}
	// 初始化富文本
	initRichText = ()=>{
		let editor =  new E(this.editorWrap.current);
		this.setState({
			editor
		},()=>{
			this.state.editor.create();
			// 设置富文本初始的值
			this.state.editor.txt.html(this.state.initArticle.content)
		})
	}
	getInitArt = ()=>{
		// 获取 编辑文章 数据
	
		 getArt(parseInt(this.props.match.params.id)).then(res=>{
			console.log(res)
			 if(res.data.code === '0'){
				 this.setState({
					 initArticle : res.data.data
				 },()=>{
					 // 初始化富文本  数据过来之后
					 this.initRichText();
				 })
			 }
		 })
	}
	submitForm =(value) =>{
	// 提交表单
		let formValue = {
			...value,
			content:this.state.editor.txt.html(),
			count:0,
			createAt:Date.now()
		}
		updateArt(formValue).then(res=>{
			if(res.data.code === '0' ){
				message.success(res.data.msg,1,()=>{
					this.props.history.go(0)
				})
			}
		})
	}
}
